﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web.UI.WebControls;
using Facebook;
using Facebook.Web;
using HairFacebookApp.DAO;
using HairFacebookApp.DTO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Dynamic;
using System.Threading;

namespace HairFacebookApp
{
    public partial class _HairSurvey : System.Web.UI.Page
    {
        //csvDao
        private CsvDao csvDao = new CsvDao();
        //
        private int currentQuestion = 1;
        private CanvasAuthorizer _canvasAuthorizer;
        protected CanvasAuthorizer CanvasAuthorizer
        {
            get
            {
                if (_canvasAuthorizer == null)
                {
                    var extendedPermissions = ConfigurationManager.AppSettings["extendedPermissions"].Split(',');
                    _canvasAuthorizer = new CanvasAuthorizer { Permissions = extendedPermissions };
                }
                return _canvasAuthorizer;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ////facebook information
            CanvasAuthorizer.Authorize();

            if (!plnGame.Visible)
            {
                backGroundDiv.Attributes.Add("style",
                    "background-image: url('Background/Intro.jpg'); padding-top: 210px;" +
                            "padding-left: 120px; padding-right: 100px; height: 750px");
            }
        }

        protected void onSelectAnswer(object sender, EventArgs e)
        {
            currentQuestion = Int32.Parse(nextQ.Value);

            //Load question
            QuestionDto q = null;

            if (currentQuestion == 2)
            {
                //Store the first answer                        
                firstA.Value = rdbListAnswer.SelectedValue;
            }

            if (currentQuestion < 6)
            {
                q = csvDao.getNextQuestion(currentQuestion, firstA.Value.ToCharArray()[0]);
                lblQuestion.Text = "Câu " + currentQuestion + ": " + q.Question;
                char c = 'A';
                if (currentQuestion == 5)
                {
                    //Save question answer key 4th
                    ques4AnsKey.Value = rdbListAnswer.SelectedValue;

                    cbxA.Text = q.Answers[0];
                    cbxB.Text = q.Answers[1];
                    cbxC.Text = q.Answers[2];
                    cbxD.Text = q.Answers[3];

                    rdbListAnswer.Visible = false;
                    pnlAnswer5.Visible = true;
                    btnNextQuestion.Visible = true;
                    btnNextQuestion.Enabled = false;

                    nextQ.Value = (currentQuestion + 1).ToString();
                }
                else
                {
                    //Save question answer key 2th, 3th
                    switch (currentQuestion)
                    {
                        case 3:
                            ques2AnsKey.Value = rdbListAnswer.SelectedValue;
                            break;
                        case 4:
                            ques3AnsKey.Value = rdbListAnswer.SelectedValue;
                            break;
                    }
                    rdbListAnswer.Items.Clear();
                    foreach (string a in q.Answers)
                    {
                        rdbListAnswer.Items.Add(new ListItem(a, c.ToString()));
                        c++;
                    }
                    //rdbListAnswer.SelectedIndex = 0;
                    nextQ.Value = (currentQuestion + 1).ToString();
                }
            }
        }
        protected void onClickNextQuestion(object sender, EventArgs e)
        {
            //No more question
            pnlQuestion.Visible = false;
            pnlResult.Visible = true;

            //based on the answer, load the corresponding background
            backGroundDiv.Style.Clear();
            switch (firstA.Value)
            {
                case "A":
                    backGroundDiv.Attributes.Add("style",
                        "background-image: url('Background/BG1.jpg'); padding-top: 40px;" +
                        "padding-left: 120px; padding-right: 100px; height: 920px");
                    break;
                case "B":
                    backGroundDiv.Attributes.Add("style",
                        "background-image: url('Background/BG2.jpg'); padding-top: 40px;" +
                        "padding-left: 120px; padding-right: 100px; height: 920px");
                    break;
                case "C":
                    backGroundDiv.Attributes.Add("style",
                        "background-image: url('Background/BG3.jpg'); padding-top: 40px;" +
                        "padding-left: 120px; padding-right: 100px; height: 920px");
                    break;
                case "D":
                    backGroundDiv.Attributes.Add("style",
                        "background-image: url('Background/BG4.jpg'); padding-top: 40px;" +
                        "padding-left: 120px; padding-right: 100px; height: 920px");
                    break;
                default:
                    break;
            }


            //Save to database
            UserDto testUser = new UserDto();
            testUser.Name = lblName.Text;
            testUser.Date = System.DateTime.Now.ToString();
            testUser.Image = hdImage.Value;
            testUser.Birthday = hdBirthday.Value;
            testUser.Place = hdPlace.Value;

            //Save question answer key 5th
            ques5AnsKey.Value = rdbListAnswer.SelectedValue;

            //Get user anwser key
            int i = 0;
            for (; i < 4; i++)
            {
                QuestionDto q1 = new QuestionDto();
                switch (i)
                {
                    case 0:
                        q1.Choose = firstA.Value.ToCharArray()[0];
                        testUser.UserAnsweredQues.Add(q1);
                        break;
                    case 1:
                        q1.Choose = ques2AnsKey.Value.ToCharArray()[0];
                        testUser.UserAnsweredQues.Add(q1);
                        break;
                    case 2:
                        q1.Choose = ques3AnsKey.Value.ToCharArray()[0];
                        testUser.UserAnsweredQues.Add(q1);
                        break;
                    case 3:
                        q1.Choose = ques4AnsKey.Value.ToCharArray()[0];
                        testUser.UserAnsweredQues.Add(q1);
                        break;
                }
            }
            //The 5th question
            QuestionDto q2 = new QuestionDto();
            string answer5 = "";
            String answer5Key = "";
            if (cbxA.Checked)
            {
                answer5 += cbxA.Text + ": " + tbxA.Text;
                answer5Key += "A";
            }
            if (cbxB.Checked)
            {
                answer5 += cbxB.Text + ": " + tbxB.Text;
                answer5Key += "B";
            }
            if (cbxC.Checked)
            {
                answer5 += cbxC.Text + ": " + tbxC.Text;
                answer5Key += "C";
            }
            if (cbxD.Checked)
            {
                answer5 += cbxD.Text + ": " + tbxD.Text;
                answer5Key += "D";
            }
            q2.No5Answer = answer5;
            q2.No5AnswerKey = answer5Key;            
            testUser.UserAnsweredQues.Add(q2);
            //Get result
            csvDao.getUserResult(testUser);
            //Show result
            lblResult.Text = testUser.Result;
            //Save to database
            csvDao.saveUserInfo(testUser);
        }
        protected void onChecked(object sender, EventArgs e)
        {
            btnNextQuestion.Enabled = cbxA.Checked || cbxB.Checked || cbxC.Checked || cbxD.Checked;
        }

        protected void onClickBtnStart(object sender, EventArgs e)
        {
            if (CanvasAuthorizer.Authorize()) {
                var fb = new FacebookWebClient();
                dynamic me = fb.Get("me");
                lblName.Text = me.name;
                hdBirthday.Value = me.birthday;
                hdImage.Value = string.Format("https://graph.facebook.com/{0}/picture", me.id);
                hdFacebookID.Value = me.id;
                if (me.location != null) {
                    hdPlace.Value = me.location.name;
                }
            }


            plnGame.Visible = true;
            btnStart.Visible = false;

            currentQuestion = Int32.Parse(nextQ.Value);
            if (currentQuestion == 1)
            {
                // Load first background
                backGroundDiv.Style.Clear();
                backGroundDiv.Attributes.Add("style",
                    "background-image: url('Background/BG.jpg'); padding-top: 210px;" +
                            "padding-left: 120px; padding-right: 100px; height: 750px");

                //Load question                
                QuestionDto q = csvDao.getFirstQuestion();

                lblQuestion.Text = "Câu " + currentQuestion + ": " + q.Question;
                char c = 'A';
                rdbListAnswer.Items.Clear();
                foreach (string a in q.Answers)
                {
                    ListItem item = new ListItem(a, c.ToString());
                    rdbListAnswer.Items.Add(item);
                    c++;
                }
                nextQ.Value = (currentQuestion + 1).ToString();
            }
        }


        protected void onClickShareToWall(object sender, EventArgs e)
        {
            if (CanvasAuthorizer.Authorize())
            {
                string uploadFileName = "";
                switch (firstA.Value)
                {
                    case "A":
                        uploadFileName = "result_1_wall.jpg";
                        break;
                    case "B":
                        uploadFileName = "result_2_wall.jpg";
                        break;
                    case "C":
                        uploadFileName = "result_3_wall.jpg";
                        break;
                    case "D":
                        uploadFileName = "result_4_wall.jpg";
                        break;
                    default:
                        break;
                }

                var fb = new FacebookWebClient();

                dynamic parameters = new ExpandoObject();

                //There is an Image to add to the parameters                
                FacebookMediaObject media = new FacebookMediaObject
                {
                    FileName = "Ket qua khao sat toc cua ban.jpg",
                    ContentType = "image/jpeg"
                };

                byte[] img = File.ReadAllBytes(Path.Combine(HttpContext.Current.Server.MapPath("Background"), uploadFileName));

                media.SetValue(img);
                parameters.message = hdShareToWallMsg.Value;
                parameters.source = media;
                try
                {
                    dynamic id = fb.Post("me/photos", parameters);
                    lblInfo.Text = "Kết quả đã được chia sẻ lên facebook";
                }
                catch (FacebookApiException ex)
                {
                    //ignore it                    
                    lblInfo.Text = "Chia sẻ không thành công:" + ex.Message;
                }
            }
        }

        protected void onClickJoinEvent(object sender, EventArgs e)
        {

        }

        protected void onClickTryProduct(object sender, EventArgs e)
        {
            //Display quay so background
            plnQuaySo.Visible = true;
            plnGame.Visible = false;
            //
            backGroundDiv.Style.Clear();
            backGroundDiv.Attributes.Add("style",
                "background-image: url('Background/quaysobackground.jpg'); padding-top: 250px;" +
                        "padding-left: 120px; padding-right: 100px; height: 750px");
            ////Temp for 10/5/2012
            //btnQuaySo.Enabled = false;
            //lblQuaySoNotice.Text = "Chương trình quay số sẽ bắt đầu vào ngày 10/5/2012" + "<br/>"
            //    + "Cơ hội sỡ hữu 1 trong 2 bộ sản phẩm Pantene bao gồm 1 chai dầu gội, 1 chai dầu xả, 1 chai kem ủ phù hợp với loại tóc của mình đang chờ đón bạn!";

            //Check on quayso Status to display result
            String strUserFBID = hdFacebookID.Value;
            //Check quay so status
            if (csvDao.checkUserQuaySoStatus(strUserFBID))
            {
                //Da nhan sp -> thong bao ko dc nhan sp nua
                btnQuaySo.Visible = false;
                lblQuaySoNotice.Text = "Bạn đã nhận được sản phẩm dùng thử!";
                btnLearnMoreQS.Visible = true;
            }
        }

        protected void onClickBtnQuaySo(object sender, EventArgs e)
        {
            //Display quay so background            
            plnQuaySo.Visible = true;
            plnGame.Visible = false;
            backGroundDiv.Style.Clear();
            backGroundDiv.Attributes.Add("style",
                "background-image: url('Background/quaysobackground.jpg'); padding-top: 250px;" +
                        "padding-left: 120px; padding-right: 100px; height: 750px");
            //Load random funtion             
            String strUserFBID = hdFacebookID.Value;
            if (csvDao.randomQuaySo())//<----For test add !
            {
                //Trung thuong
                btnQuaySo.Visible = false;
                lblQuaySoNotice.Text = "Chúc mừng bạn đã may mắn trúng được bộ sản phẩm dùng thử tương ứng với loại tóc của mình!" + "<br/>" +
                    "Vui lòng điền đầy đủ thông tin bên dưới để chúng tôi có thể gửi sản phẩm dùng thử cho bạn.";
                tblQuaySoSubmit.Visible = true;
            }
            else
            {
                //Ko trung thuong
                btnQuaySo.Visible = false;
                lblQuaySoNotice.Text = "Chúc bạn may mắn lần sau!";
                btnLearnMoreQS.Visible = true;
            }
        }

        protected void onClickBtnQSSubmit(object sender, EventArgs e)
        {
            //Display quay so background            
            plnQuaySo.Visible = true;
            plnGame.Visible = false;
            backGroundDiv.Style.Clear();
            backGroundDiv.Attributes.Add("style",
                "background-image: url('Background/quaysobackground.jpg'); padding-top: 250px;" +
                        "padding-left: 120px; padding-right: 100px; height: 750px");
            //Check value of input information
            if (String.Compare(qsName.Text, "") == 0 || String.Compare(qsAddress.Text, "") == 0 || String.Compare(qsPhone.Text, "") == 0 || String.Compare(qsEmail.Text, "") == 0)
                lblQuaySoNotice.Text = "Vui lòng điền đầy đủ thông tin để chúng tôi có thể gửi sản phẩm thừ cho bạn một cách chính xác, nhanh chóng nhất!";
            else
            {
                tblQuaySoSubmit.Visible = false;
                lblQuaySoNotice.Text = "Cám ơn bạn đã tham gia chương trình!";
                btnLearnMoreQS.Visible = true;
                //Save to database
                QuaySoDto quaysoDto = new QuaySoDto();
                quaysoDto.Name = qsName.Text;
                quaysoDto.FacebookID = hdFacebookID.Value;
                quaysoDto.Address = qsAddress.Text;
                quaysoDto.Phone = qsPhone.Text;
                quaysoDto.Email = qsEmail.Text;
                quaysoDto.Quayso = '1';
                quaysoDto.Date = DateTime.Today.ToString("d");
                switch (firstA.Value)
                {
                    case "A":
                        quaysoDto.Result = "Tóc khô";
                        break;
                    case "B":
                        quaysoDto.Result = "Tóc hư tổn, chẻ ngọn";
                        break;
                    case "C":
                        quaysoDto.Result = "Tóc rụng";
                        break;
                    case "D":
                        quaysoDto.Result = "Tóc thiếu độ phồng";
                        break;
                }
                //Save to quaysoDto file
                csvDao.saveQuaySoInfo(quaysoDto);
            }
        }
    }
}
